<script lang="ts" setup>
import { computed, ref, watch, nextTick, useSlots, useAttrs } from "vue";
import { isNumber } from "./helper";

defineOptions({ name: "Dialog" });

export interface DialogProps {
  modelValue?: boolean;
  title?: string;
  fullscreen?: boolean;
  width?: string | number;
  scroll?: boolean;
  maxHeight?: string | number;
}

const props = withDefaults(defineProps<DialogProps>(), {
  modelValue: false,
  title: "Dialog",
  fullscreen: true,
  width: "40%",
  scroll: false,
  maxHeight: "400px",
});

const slots = useSlots();

const getBindValue = computed(() => {
  const delArr: string[] = ["fullscreen", "title", "maxHeight", "appendToBody"];
  const attrs = useAttrs();
  const obj: Record<string, any> = { ...attrs, ...props };
  for (const key in obj) {
    if (delArr.indexOf(key) !== -1) {
      delete obj[key];
    }
  }
  return obj;
});

const isFullscreen = ref(false);
defineExpose({ isFullscreen });
const toggleFull = () => {
  isFullscreen.value = !unref(isFullscreen);
};

const dialogHeight = ref(
  isNumber(props.maxHeight) ? `${props.maxHeight}px` : props.maxHeight
);

watch(
  () => isFullscreen.value,
  async (val: boolean) => {
    await nextTick();
    if (val) {
      const windowHeight = document.documentElement.offsetHeight;
      dialogHeight.value = `${
        windowHeight - 55 - 60 - (slots.footer ? 63 : 0)
      }px`;
    } else {
      dialogHeight.value = isNumber(props.maxHeight)
        ? `${props.maxHeight}px`
        : props.maxHeight;
    }
  },
  {
    immediate: true,
  }
);

const dialogStyle = computed(() => {
  return {
    height: unref(dialogHeight),
  };
});
</script>

<template>
  <ElDialog
    v-bind="getBindValue"
    :close-on-click-modal="true"
    :fullscreen="isFullscreen"
    :width="width"
    destroy-on-close
    lock-scroll
    draggable
    class="com-dialog"
    :show-close="false"
  >
    <template #header="{ close }">
      <div class="com-dialog-header">
        <slot name="title">
          {{ title }}
        </slot>
        <div class="com-dialog-header-actions">
          <span
            v-if="fullscreen"
            class="com-dialog-header-action"
            :class="
              isFullscreen
                ? 'i-ri-fullscreen-exit-line'
                : 'i-ri-fullscreen-line'
            "
            @click="toggleFull"
          ></span>
          <span
            class="com-dialog-header-action i-ri-close-line"
            @click="close"
          ></span>
        </div>
      </div>
    </template>

    <ElScrollbar v-if="scroll" :style="dialogStyle">
      <slot></slot>
    </ElScrollbar>
    <slot v-else></slot>
    <template v-if="slots.footer" #footer>
      <slot name="footer"></slot>
    </template>
  </ElDialog>
</template>

<style lang="scss">
@use "./Dialog.scss";
</style>
